import { NavBar, Input, Button, Toast } from 'antd-mobile'
import React, { useState } from 'react'
import { initFn } from '@/hooks/useCommon'
import styles from "./index.module.less"
import { showErrorToast, showSuccessToast } from '@/utils/customToast'
const { getLogin } = $globalServicer('login')
import logoSvg from '@/assets/icons/logo-text-enhanced.svg'
const { getUserInfo } = $globalServicer('My')
const { setShopNum, setNotificationUnread } = $globalReduxAction('common')
import storage from '../../utils/storage'
import Cookies from 'js-cookie'
const Login = () => {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const customNavigate = $globalNavigate()
  console.log(`login version:`, __APP_VERSION__)
  const submitLogin = () => {
    // initFn()
    // navigate('/home', { replace: true })
    getLoginInfo()
  }
  const validateEmail = (email) => {
    var emailRegex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/;
    return emailRegex.test(email);
  }
  const getLoginInfo = async () => {
    // 输入验证
    if (!email.trim()) {
      showErrorToast('请输入邮箱')
      return
    }
    
    if (!password.trim()) {
      showErrorToast('请输入密码')
      return
    }

    const isEmailValid = validateEmail(email)
    if (!isEmailValid) {
      showErrorToast('邮箱格式不正确')
      return
    }

    try {
      // 显示加载提示
      Toast.show({
        icon: 'loading',
        content: '登录中...',
        duration: 0
      })

      console.log(`登录请求参数:`, { email, password })
      
      const res = await getLogin({
        email,
        password
      })
      
      // 隐藏加载提示
      Toast.clear()
      
      if (res && res.access_token) {
        const { access_token, expires_in, token_type } = res
        storage.set('access_token', access_token)
        storage.set('expires_in', expires_in)
        storage.set('token_type', token_type)
        
        // 登录成功后获取用户信息，检查通知未读状态
        try {
          const userInfo = await getUserInfo()
          console.log('用户信息:', userInfo)
          // 检查用户信息中的is_read字段
          if (userInfo && userInfo.user && userInfo.user.is_read !== undefined) {
            // 如果is_read字段为0，显示小红点
            setNotificationUnread(userInfo.user.is_read === 0)
          }
        } catch (userInfoError) {
          console.error('获取用户信息失败:', userInfoError)
          // 获取用户信息失败不影响登录流程
        }
        
        showSuccessToast('登录成功')
        
        // 延迟跳转，确保Redux状态更新完成
        setTimeout(() => {
          customNavigate('/home', { replace: true })
        }, 100)
      } else {
        showErrorToast('登录失败：服务器返回数据异常')
      }
    } catch (error) {
      // 隐藏加载提示
      Toast.clear()
      
      console.error('登录错误:', error)
      
      // 根据错误类型显示不同提示
      let errorMessage = '登录失败'
      
      if (error.message) {
        if (error.message.includes('Network Error') || error.message.includes('网络连接异常')) {
          errorMessage = '网络连接失败，请检查网络连接'
        } else if (error.message.includes('timeout') || error.message.includes('加载慢')) {
          errorMessage = '请求超时，请重试'
        } else if (error.message.includes('401') || error.message.includes('unauthorized')) {
          errorMessage = '邮箱或密码错误'
        } else if (error.message.includes('500')) {
          errorMessage = '服务器错误，请稍后重试'
        } else {
          errorMessage = error.message || '登录失败，请重试'
        }
      }
      
      showErrorToast(errorMessage)
    }
  }
  return (
    <div className={styles.login_page}>
      {/* Logo区域 */}
      <div className={styles.logoSection}>
        <img
          src={logoSvg}
          alt="AI物语" 
          className={styles.logo}
        />
      </div>

      {/* 主要内容区域 */}
      <div className={styles.mainContent}>
        {/* 邮箱输入 */}
        <div className={styles.inputGroup}>
          <label className={styles.inputLabel} htmlFor="email">邮箱名</label>
          <Input
            id="email"
            className={styles.emailInput}
            placeholder="请输入邮箱名"
            value={email}
            clearable
            onChange={val => setEmail(val)}
            type="email"
          />
        </div>

        {/* 密码输入 */}
        <div className={styles.inputGroup}>
          <label className={styles.inputLabel} htmlFor="password">密码</label>
          <Input
            id="password"
            className={styles.passwordInput}
            placeholder="请输入密码"
            value={password}
            clearable
            onChange={val => setPassword(val)}
            type="password"
          />
        </div>

        {/* 登录按钮 */}
        <div className={styles.loginButtonGroup}>
          <Button className={styles.loginButton} onClick={submitLogin}>
            登录
          </Button>
        </div>

        {/* 注册链接 */}
        <div className={styles.registerLink}>
          <p className={styles.registerText}>
            还没有账号？ <span className={styles.registerSpan} onClick={() => customNavigate('/register')}>立即注册</span>
          </p>
        </div>
      </div>
    </div>
  );
};

export default Login;
